package com.zdp.controller;

import com.zdp.api.controller.files.FileUploaderControllerApi;
import com.zdp.config.FileResources;
import com.zdp.grace.result.GraceJSONResult;
import com.zdp.grace.result.ResponseStatusEnum;
import com.zdp.utils.MinioOperator;
import com.zdp.utils.extend.AliImageReviewUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author sesshomaru
 * @date 2021/5/25
 */
@RestController
public class FileUploaderController implements FileUploaderControllerApi {

    final static Logger logger = LoggerFactory.getLogger(FileUploaderController.class);

    @Autowired
    private MinioOperator minioOperator;

    @Autowired
    private FileResources fileResources;

    @Autowired
    private AliImageReviewUtils aliImageReviewUtils;

    @Override
    public GraceJSONResult uploadFace(String userId, MultipartFile file) throws Exception {
        if (file != null) {
            // 获取文件上传的名称
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                String fileNameArr[] = fileName.split("\\.");

                // 获取文件的后缀名
                String suffix = fileNameArr[fileNameArr.length - 1];

                if (!suffix.equalsIgnoreCase("png") &&
                        !suffix.equalsIgnoreCase("jpg") &&
                        !suffix.equalsIgnoreCase("jpeg") ) {
                    return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
                }
                String objectName = UUID.randomUUID().toString() + "." + suffix;
                String bucketName = "test";
                // http://39.106.77.123/re/ + test/8341f05e-5801-4ae0-aeb0-ddb7ebedb16b.jpg = http://39.106.77.123/re/test/8341f05e-5801-4ae0-aeb0-ddb7ebedb16b.jpg
                String finalPath = fileResources.getHost() +
                        minioOperator.uploadToMinio(bucketName, objectName, file.getInputStream());
                logger.info("文件名:{}", objectName);
                logger.info("数据桶:{}", bucketName);
                logger.info("访问地址:{}", finalPath);

                // 添加上图片安全校验,安全则返回图片最终的访问地址失败则返回对应的内容不安全提示的错误图片
                // TODO 待有阿里图片安全校验服务时启用内容安全校验
                // return GraceJSONResult.ok(doAliImagReview(finalPath));

                return GraceJSONResult.ok(finalPath);
            }
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        return GraceJSONResult.ok();
    }

    @Override
    public GraceJSONResult uploadSomeFiles(String userId, MultipartFile[] files) throws Exception {
        // 声明list，用于存放多个图片的地址路径，返回到前端
        List<String> imageUrlList = new ArrayList<>();
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                String path = "";
                if (file != null) {
                    // 获得文件上传的名称
                    String fileName = file.getOriginalFilename();

                    // 判断文件名不能为空
                    if (StringUtils.isNotBlank(fileName)) {
                        String fileNameArr[] = fileName.split("\\.");
                        // 获得后缀
                        String suffix = fileNameArr[fileNameArr.length - 1];
                        // 判断后缀符合我们的预定义规范
                        if (!suffix.equalsIgnoreCase("png") &&
                                !suffix.equalsIgnoreCase("jpg") &&
                                !suffix.equalsIgnoreCase("jpeg")
                        ) {
                            continue;
                        }
                        // 执行上传
                        String objectName = UUID.randomUUID().toString() + "." + suffix;
                        String bucketName = "test";
                        // http://39.106.77.123/re/ + test/8341f05e-5801-4ae0-aeb0-ddb7ebedb16b.jpg = http://39.106.77.123/re/test/8341f05e-5801-4ae0-aeb0-ddb7ebedb16b.jpg
                        String finalPath = fileResources.getHost() +
                                minioOperator.uploadToMinio(bucketName, objectName, file.getInputStream());
                        logger.info("文件名:{}", objectName);
                        logger.info("数据桶:{}", bucketName);
                        logger.info("访问地址:{}", finalPath);

                        //FIXME 前端也会针对返回回去的list和上传的files长度进行比较如果个数有差就会提示用户有多少张图片上传失败
                        // 内容安全校验 出现非法图片就会用户非法的提示图片替换上传的图片
                        // finalPath = doAliImagReview(finalPath);

                        imageUrlList.add(finalPath);
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }
            }
        }
        return GraceJSONResult.ok(imageUrlList);
    }

    // 图片安全校验失败时返回的错误图片
    public static final String FAILED_IMAGE_URL = "https://imooc-news.oss-cn-shanghai.aliyuncs.com/image/faild.jpeg";
    // 使用阿里图片内容安全api校验
    private String doAliImagReview(String finalPath) {
        boolean result = false;
        try {
            result = aliImageReviewUtils.reviewImage(finalPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 图片不安全返回错误提示图片
        if (!result) {
            return FAILED_IMAGE_URL;
        }
        return finalPath;
    }
}
